package com.schoolcloud.files.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.schoolcloud.files.entity.StorageBucket;
import com.schoolcloud.files.service.StorageBucketService;
import com.schoolcloud.files.mapper.StorageBucketMapper;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.SetBucketPolicyArgs;
import io.minio.errors.MinioException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;

/**
* @author hongmizfb
* @description 针对表【storage_bucket(存储桶配置表)】的数据库操作Service实现
* @createDate 2025-07-19 16:18:37
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class StorageBucketServiceImpl extends ServiceImpl<StorageBucketMapper, StorageBucket>
    implements StorageBucketService{
    private final MinioClient minioClient;
    @Override
    public boolean createBucket(StorageBucket storageBucket) {
        // 1. 校验存储类型是否为 MinIO
        if (!"minio".equals(storageBucket.getStorageType())) {
            throw new IllegalArgumentException("当前方法仅支持 MinIO 存储类型");
        }
        String bucketName = storageBucket.getBucketName();
        try {
            // 2. 检查存储桶是否已存在
            boolean exists = minioClient.bucketExists(
                    BucketExistsArgs.builder().bucket(bucketName).build()
            );
            if (!exists) {
                // 3. 创建存储桶（支持指定区域）
                MakeBucketArgs.Builder bucketBuilder = MakeBucketArgs.builder().bucket(bucketName);
                // 如果指定了区域，则添加区域参数（MinIO 服务器需支持区域配置）
                if (StringUtils.hasText(storageBucket.getRegion())) {
                    bucketBuilder.region(storageBucket.getRegion());
                }
                minioClient.makeBucket(bucketBuilder.build());
                minioClient.setBucketPolicy(
                        SetBucketPolicyArgs.builder()
                                .bucket(bucketName)
                                .build()
                );
            }
            storageBucket.setCreateTime(LocalDateTime.now());
            storageBucket.setUpdateTime(LocalDateTime.now());
            save(storageBucket);
            return true;
        } catch (Exception e) {
            log.error("MinIO 创建存储桶失败：{}", e.getMessage());
            e.printStackTrace();
        }
        return false;
    }
}




